package com.hhkj.study.admin.order.service.biz.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.hhkj.study.admin.order.entity.Order;
import com.hhkj.study.admin.order.entity.OrderItem;
import com.hhkj.study.admin.order.enums.OrderStatusEnum;
import com.hhkj.study.admin.order.excel.OrderItemExcelRes;
import com.hhkj.study.admin.order.model.podo.OrderDo;
import com.hhkj.study.admin.order.model.podo.OrderItemDo;
import com.hhkj.study.admin.order.model.podo.OrderItemPo;
import com.hhkj.study.admin.order.model.podo.OrderPo;
import com.hhkj.study.admin.order.model.req.OrderReq;
import com.hhkj.study.admin.order.model.res.OrderRes;
import com.hhkj.study.admin.order.service.base.OrderItemService;
import com.hhkj.study.admin.order.service.base.OrderService;
import com.hhkj.study.admin.order.service.biz.OrderBizService;
import com.hhkj.study.admin.order.service.biz.OrderItemBizService;
import com.hhkj.study.admin.order.service.extend.OrderExtendService;
import com.hhkj.study.admin.resource.common.CommonValidateHandler;
import com.hhkj.study.admin.resource.excel.BaseExcelRes;
import com.hhkj.study.api.user.sevice.biz.ApiUserCourseBizService;
import com.hhkj.study.common.cache.GlobalCache;
import com.hhkj.study.common.logic.OrderInfoCreator;
import com.hhkj.study.common.model.res.ExcelImportResultRes;
import com.ruoyi.common.base.biz.service.biz.BaseBizServiceImpl;
import com.ruoyi.common.cont.SysConst;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.excl.utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* OrderBizServiceImpl
*
* @author SERVER
* @since 2024-09-18
*/
@Slf4j
@Service
public class OrderBizServiceImpl extends BaseBizServiceImpl<Order, OrderReq, OrderRes, OrderDo, OrderPo, OrderService, OrderExtendService> implements OrderBizService {

    @Resource
    private OrderItemBizService orderItemBizService;

    @Resource
    private OrderItemService orderItemService;

    @Resource
    private GlobalCache globalCache;

    @Resource
    private ApiUserCourseBizService apiUserCourseBizService;

    @Resource
    private CommonValidateHandler commonValidateHandler;

    @Override
    protected void beforeSave(OrderReq orderReq) {
        super.beforeSave(orderReq);
        Integer enterpriseFlag = orderReq.getEnterpriseFlag();
        if (enterpriseFlag == null) {
            orderReq.setEnterpriseFlag(0);
        }

        Integer payStatusFlag = orderReq.getPayStatusFlag();
        if (payStatusFlag == null) {
            orderReq.setPayStatusFlag(1);
            orderReq.setOrderStatus(OrderStatusEnum.PAID.getCode());
        }
        orderReq.setOrderCode(OrderInfoCreator.createCode(orderReq));
    }

    @Override
    protected void afterSave(OrderReq orderReq) {
        super.afterSave(orderReq);

        List<OrderItem> orderItemList = orderItemBizService.saveBatchAndAssignUser(orderReq.getId(), orderReq.getItemList());
        // 用户下单后默认生成用户学习记录 建培圈系统数据
        asyncSaveUserDefaultRecordAndTrainSystem(orderItemList, orderReq);
    }

    @Override
    protected void afterGetById(OrderRes orderRes) {
        super.afterGetById(orderRes);

        OrderItemDo orderItemDo = new OrderItemDo();
        orderItemDo.setOrderId(orderRes.getId());
        List<OrderItemPo> orderItemList = orderItemService.listPoByDo(orderItemDo);
        orderRes.setItemList(orderItemList);
    }


    /**
     * 异步生成用户默认记录
     * @param itemList
     */
    @Async("discoveryExecutor")
    public void asyncSaveUserDefaultRecordAndTrainSystem(List<OrderItem> itemList, OrderReq orderReq){
        if (CollectionUtil.isEmpty(itemList)) {
            return;
        }
        log.warn("异步生成用户记录中...,用户订单号为{},用户手机号为{}", orderReq.getId(), orderReq.getPayUserMobile());
        List<OrderItemDo> orderItemDoList = BeanUtil.copyToList(itemList, OrderItemDo.class);
        apiUserCourseBizService.userCourseStudyRecordSave(orderItemDoList);

        // 生成建培圈用户课程关联数据
        apiUserCourseBizService.userCourseGenerateOutSystemAccount(orderItemDoList);
    }

    /**
     * 导入用户订单
     * @param file
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ExcelImportResultRes importUserOrder(MultipartFile file, HttpServletRequest request) {
        List<OrderItemExcelRes> orderExcelResList = ExcelUtils.importExcelRuoYi(file, OrderItemExcelRes.class, 1);
        if (CollectionUtil.isEmpty(orderExcelResList)) {
            throw new GlobalException("没有数据");
        }
        ExcelImportResultRes excelImportResultRes = commonValidateHandler.commonValidate(orderExcelResList, this::checkUnion);
        // 没有报错信息则进行业务操作
        if (CollectionUtil.isEmpty(excelImportResultRes.getErrorList())) {
            // 构建订单生成参数
            orderExcelResList.forEach(orderItemExcelRes -> {
                OrderReq orderReq = this.setOrderInfo(orderItemExcelRes);
                // 保存订单
                this.save(orderReq);
            });
        }
        return excelImportResultRes;
    }

    /**
     * 暂时放到该处 后续可能要做唯一判断
     * @param res
     */
    public void checkUnion(BaseExcelRes res){

    }

    /**
     * 订单和子订单赋值
     * @param orderItemExcelRes
     * @return
     */
    private OrderReq setOrderInfo(OrderItemExcelRes orderItemExcelRes){
        // 订单信息赋值
        OrderReq orderReq = new OrderReq();
        orderReq.setPayType(orderItemExcelRes.getPayType());
        orderReq.setPayUserName(orderItemExcelRes.getBuyerName());
        orderReq.setSaleName(orderItemExcelRes.getSaleName());
        orderReq.setEnterpriseFlag(ObjectUtil.isNull(orderItemExcelRes.getEnterpriseFlag()) ? SysConst.Flag.IS.getFlag() : SysConst.Flag.NO.getFlag());
        orderReq.setPayPrice(orderItemExcelRes.getPayPrice());
        orderReq.setRemark(orderItemExcelRes.getRemark());
        orderReq.setPayTime(orderItemExcelRes.getPayTime());

        // 子订单赋值
        Map<Long, String> goodsSkuMap = globalCache.cacheParentGoodsMap();
        OrderItemPo orderItemPo = new OrderItemPo();
        orderItemPo.setBuyerName(orderItemExcelRes.getBuyerName());
        orderItemPo.setBuyerMobile(orderItemExcelRes.getBuyerMobile());
        orderItemPo.setOriginPrice(orderItemExcelRes.getOriginPrice());
        orderItemPo.setPayPrice(orderItemExcelRes.getPayPrice());
        orderItemPo.setGoodsSkuId(orderItemExcelRes.getGoodsSkuId());
        orderItemPo.setGoodsName(CollectionUtil.getFirst(StrUtil.split(goodsSkuMap.get(orderItemExcelRes.getGoodsSkuId()), StrUtil.DASHED)));

        orderReq.setItemList(Lists.newArrayList(orderItemPo));
        return orderReq;
    }
}